<template>
  <div class="flex items-center cursor-pointer" @click="handleGo">
    <el-icon>
      <ArrowLeftBold />
    </el-icon>
    <span class="pl-5">{{ currentId ? $t("编辑客户") : $t("添加客户") }}</span>
  </div>
  <div class="mt-6">
    <h3 class="mb-4">{{ $t("企业信息") }}</h3>
    <el-card>
      <el-form
        label-position="left"
        label-width="auto"
        :model="state.accountInfo"
        :rules="rules"
        ref="companyFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('企业名称')" prop="company_name">
              <el-input
                v-model="state.accountInfo.company_name"
                :placeholder="$t('请输入企业名称')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('银行名称')" prop="bank_name">
              <el-input
                v-model="state.accountInfo.bank_name"
                :placeholder="$t('请输入银行名称')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('银行账号')" prop="card_number">
              <el-input
                v-model="state.accountInfo.card_number"
                :placeholder="$t('请输入银行账号')"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('银行国家/地区')" prop="bank_country">
              <el-select
                v-model="state.accountInfo.bank_country"
                :placeholder="$t('请输入银行国家/地区')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in state.countryList"
                  :key="item.jc"
                  :label="item.country"
                  :value="item.jc"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('银行账号名称')" prop="card_name">
              <el-input
                :placeholder="$t('请输入银行账号名称')"
                v-model="state.accountInfo.card_name"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('银行地址')" prop="bank_address">
              <el-input
                :placeholder="$t('请输入银行地址')"
                v-model="state.accountInfo.bank_address"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('持卡人国家')" prop="card_country">
              <el-select
                v-model="state.accountInfo.card_country"
                :placeholder="$t('VA-请选择持卡人国家')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in state.countryList"
                  :key="item.jc"
                  :label="item.country"
                  :value="item.jc"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('账户币种')" prop="currency">
              <el-select
                v-model="state.accountInfo.currency"
                :placeholder="$t('VA-请选择账户币种')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in state.currencyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('持卡人地址')" prop="card_address">
              <el-input
                v-model="state.accountInfo.card_address"
                :placeholder="$t('VA-请输入持卡人地址')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
  <div class="mt-6">
    <h3 class="mb-4">{{ $t("个人信息") }}</h3>
    <el-card>
      <el-form
        label-position="left"
        label-width="auto"
        :model="state.accountInfo"
        :rules="rules"
        ref="userFormRef"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('真实姓名')" prop="real_name">
              <el-input
                v-model="state.accountInfo.real_name"
                :placeholder="$t('请输入姓名全称')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('联系方式')" prop="contact">
              <el-input
                v-model="state.accountInfo.contact"
                :placeholder="$t('请输入手机号')"
                type="number"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        label-position="top"
        label-width="auto"
        :model="state.accountInfo"
        :rules="rules"
        ref="userCardRef"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('个人证件照')" prop="idCard">
              <div
                class="el-upload--picture-card el-upload-list el-upload-list--picture-card"
                v-if="state.file_idcard_front && !fileIdcardFrontBtn"
              >
                <div class="el-upload-list__item is-success">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="state.file_idcard_front"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(state.file_idcard_front, '正面')"
                    >
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </div>
              <el-upload
                ref="fileIdcardFrontRef"
                :class="{ front_box: fileIdcardFrontBtn }"
                :action="config.img_upload"
                list-type="picture-card"
                :limit="1"
                :on-success="handleFrontImgSuccess"
                :on-change="
                  (file) => {
                    handleChange(file, '正面');
                  }
                "
                v-else
                :headers="TOKENT_HEADER"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <div class="text-center">
                  {{ $t("VA-请上传个人证件正面图片") }}
                </div>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file, '正面')"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              <div class="uploadDiv" />
              <div
                class="el-upload--picture-card el-upload-list el-upload-list--picture-card"
                v-if="state.file_idcard_back && !fileIdcardBackBtn"
              >
                <div class="el-upload-list__item is-success">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="state.file_idcard_back"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(state.file_idcard_back, '反面')"
                    >
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </div>
              <el-upload
                ref="fileIdcardBackRef"
                v-else
                :class="{ back_box: fileIdcardBackBtn }"
                :action="config.img_upload"
                list-type="picture-card"
                :on-success="handleBackImgSuccess"
                :limit="1"
                :on-change="
                  (file) => {
                    handleChange(file, '反面');
                  }
                "
                :headers="TOKENT_HEADER"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <div class="text-center">
                  {{ $t("VA-请上传个人证件背面图片") }}
                </div>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file, '反面')"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              <div class="uploadDiv" />
              <div
                class="el-upload--picture-card el-upload-list el-upload-list--picture-card"
                v-if="state.file_idcard_hand && !fileIdcardHandBtn"
              >
                <div class="el-upload-list__item is-success">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="state.file_idcard_hand"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(state.file_idcard_hand, '手持')"
                    >
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </div>

              <el-upload
                v-else
                ref="fileIdcardHandRef"
                :class="{ hand_box: fileIdcardHandBtn }"
                :action="config.img_upload"
                list-type="picture-card"
                :on-success="handleHandImgSuccess"
                :limit="1"
                :on-change="
                  (file) => {
                    handleChange(file, '手持');
                  }
                "
                :headers="TOKENT_HEADER"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <div class="text-center">{{ $t("VA-请上传手持证件图片") }}</div>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file, '手持')"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
  <div class="flex justify-start mt-6">
    <h3 class="mb-4">{{ $t("提交KYC资料") }}</h3>
    <p class="ml-20">
      {{ $t("以下KYC资料请发送至邮箱:") }}
      wanglu@travel-linker.com
      {{ $t("KYC资料邮件名称:xx LTD.KYC资料") }}
    </p>
  </div>
  <el-card class="companyInfo">
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("公司注册证书") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("公司组织架构") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("最新商业登记证") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("公司地址证明(近3个月)") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("最新年审报告") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("银行对账单(近3个月)") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("最新财务报表/税表") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("采购供应商协议及发票（有效期内）") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("所有持股10%以上股东的有效証件") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("销售收入协议及发票（有效期内）") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("INVOICE范本") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("开户授权签字人有效证件+签字印鉴") }}</p>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <p>{{ $t("董事地址证明(近3个月)") }}</p>
      </el-col>
      <el-col :span="12">
        <p>{{ $t("开户授权签字人个人地址证明（近3个月）") }}</p>
      </el-col>
    </el-row>
  </el-card>
  <div class="flex justify-center mt-6">
    <el-button
      type="primary"
      @click="submitReview"
      size="large"
      class="submitBtn"
      >{{ $t("VA-提交审核") }}</el-button
    >
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import {
  GetPhoneAreaCode,
  GetVaBankCurrency,
  CreateCustomer,
} from "@/api/VAAccount";
import { config, TOKENT_HEADER } from "@/config/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { getUserInfo } from "@/api/VAAccount";

const router = useRouter();

const state = reactive({
  currencyList: [],
  countryList: [],
  accountInfo: {
    id: 0,
    company_name: "",
    bank_name: "",
    card_number: "",
    bank_country: "",
    card_name: "",
    bank_address: "",
    card_country: "",
    currency: "",
    card_address: "",
    real_name: "",
    contact: "",
    file_idcard_front: "",
    file_idcard_back: "",
    file_idcard_hand: "",
  },
  companyInfo: {},
  file_idcard_front: "",
  file_idcard_back: "",
  file_idcard_hand: "",
});

const fileIdcardFrontRef = ref(); //身份证正面Ref 用于清楚删除操作
const fileIdcardBackRef = ref(); //身份证反面Ref 用于清楚删除操作
const fileIdcardHandRef = ref(); //手持身份证Ref 用于清楚删除操作
const fileIdcardFrontBtn = ref(false); //身份证正面class 用于上传以后隐藏上传按钮
const fileIdcardBackBtn = ref(false); //身份证反面class 用于上传以后隐藏上传按钮
const fileIdcardHandBtn = ref(false); //手持身份证class 用于上传以后隐藏上传按钮

const rules = reactive({
  company_name: [
    {
      required: true,
      message: t("请输入企业名称"),
      trigger: "change",
    },
  ],
  card_number: [
    {
      required: true,
      message: t("请输入银行账号"),
      trigger: "change",
    },
  ],
  bank_name: [
    {
      required: true,
      message: t("请输入银行名称"),
      trigger: "change",
    },
  ],
  card_name: [
    {
      required: true,
      message: t("请输入银行账号名称"),
      trigger: "change",
    },
  ],
  bank_country: [
    {
      required: true,
      message: t("请选择银行国家/地区"),
      trigger: "change",
    },
  ],
  card_country: [
    {
      required: true,
      message: t("请选择持卡人国家"),
      trigger: "change",
    },
  ],
  currency: [
    {
      required: true,
      message: t("请选择币种"),
      trigger: "change",
    },
  ],
  bank_address: [
    {
      required: true,
      message: t("请输入银行地址"),
      trigger: "change",
    },
  ],
  card_address: [
    {
      required: true,
      message: t("请输入持卡人地址"),
      trigger: "change",
    },
  ],
  real_name: [
    {
      required: true,
      message: t("请输入企业名称"),
      trigger: "change",
    },
  ],
  contact: [
    {
      required: true,
      message: t("请输入手机号"),
      trigger: "change",
    },
    { min: 6, max: 16, message: t("请输入6-16位的数字"), trigger: "change" },
  ],
  //   idCard: [
  //     {
  //       required: true,
  //       message: "",
  //     },
  //   ],
});

const currentId = ref();

const handleGo = () => {
  router.replace(`/VAAccount/userList`);
};

const handleFrontImgSuccess = (res) => {
  if (res.code === 0) {
    ElMessage({
      message: t("上传成功"),
      type: "success",
    });
    state.accountInfo.file_idcard_front = res.data.name;
  } else {
    ElMessage({
      message: t("上传失败"),
      type: "error",
    });
    return false;
  }
};

// 个人证件反面照片上传成功
const handleBackImgSuccess = (res) => {
  if (res.code === 0) {
    ElMessage({
      message: t("上传成功"),
      type: "success",
    });
    state.accountInfo.file_idcard_back = res.data.name;
  } else {
    ElMessage({
      message: t("上传失败"),
      type: "error",
    });
    return false;
  }
};
// 个人证件手持上传成功
const handleHandImgSuccess = (res) => {
  if (res.code === 0) {
    ElMessage({
      message: t("上传成功"),
      type: "success",
    });
    state.accountInfo.file_idcard_hand = res.data.name;
  } else {
    ElMessage({
      message: t("上传失败"),
      type: "error",
    });
    return false;
  }
};
const handleChange = (file, type) => {
  // console.log(file);
  switch (type) {
    case "正面":
      fileIdcardFrontBtn.value = true;
      break;
    case "反面":
      fileIdcardBackBtn.value = true;
      break;
    case "手持":
      fileIdcardHandBtn.value = true;
      break;
  }
};
const handleRemove = (file, type) => {
  switch (type) {
    case "正面":
      fileIdcardFrontRef.value ? fileIdcardFrontRef.value.clearFiles() : "";
      fileIdcardFrontBtn.value = false;
      state.accountInfo.file_idcard_front = "";
      state.file_idcard_front = "";
      break;
    case "反面":
      fileIdcardBackRef.value ? fileIdcardBackRef.value.clearFiles() : "";
      fileIdcardBackBtn.value = false;
      state.accountInfo.file_idcard_back = "";
      state.file_idcard_back = "";
      break;
    case "手持":
      fileIdcardHandRef.value ? fileIdcardHandRef.value.clearFiles() : "";
      fileIdcardHandBtn.value = false;
      state.accountInfo.file_idcard_hand = "";
      state.file_idcard_hand = "";
      break;
  }
};

const companyFormRef = ref();
const userFormRef = ref();
const userCardRef = ref();

const submitReview = async () => {
  const forms = [companyFormRef.value, userFormRef.value, userCardRef.value];
  let isValid = true;
  // 遍历所有表单，依次进行验证
  for (let i = 0; i < forms.length; i++) {
    const form = forms[i];
    // 调用表单实例的 validate 方法进行验证，并等待验证完成
    await validateForm(i);
    // 如果存在任何表单验证失败，则置 isValid 为 false
    if (!form.valid) {
      isValid = false;
    }
  }
  if (isValid) {
    if (state.accountInfo.file_idcard_front === "") {
      ElMessage({
        message: t("请上传身份证正面照片"),
        type: "error",
      });
      return;
    } else if (state.accountInfo.file_idcard_back === "") {
      ElMessage({
        message: t("请上传身份证反面照片"),
        type: "error",
      });
      return;
    } else if (state.accountInfo.file_idcard_hand === "") {
      ElMessage({
        message: t("请上传手持身份证照片"),
        type: "error",
      });
      return;
    }
    if (currentId.value) {
      state.accountInfo.id = currentId.value;
    }
    const params = { ...state.accountInfo };
    ElMessageBox.confirm(`${t("提交审核")}?`, "", {
      confirmButtonText: t("VA-确认"),
      cancelButtonText: t("VA-取消"),
      center: true,
    })
      .then(() => {
        CreateCustomer(params)
          .then((res) => {
            ElMessageBox.confirm(t("提交成功, 请等待审核"), {
              confirmButtonText: "OK",
              center: true,
              showCancelButton: false, // 不展示取消按钮
            })
              .then(() => {
                // 判断是否从付款过来的
                if (history.state.isPayment) {
                  const data = { isAddCustomer: true, id: res.id };
                  router.push({
                    path: `/VAAccount/accountInfo`,
                    state: data,
                  });
                } else {
                  handleGo();
                }
              })
              .catch(() => {});
          })
          .catch(() => {
            ElMessage({
              message: t("提交审核失败"),
              type: "error",
            });
          })
          .catch(() => {});
      })
      .catch(() => {
        ElMessage({
          message: t("取消"),
          type: "info",
        });
      });
  } else {
    ElMessage({
      message: t("请检查填写信息"),
      type: "error",
    });
  }
};

const validateForm = (index) => {
  const forms = [companyFormRef.value, userFormRef.value, userCardRef.value];
  return new Promise((resolve) => {
    // 调用表单实例的 validate 方法进行验证
    forms[index].validate((valid) => {
      // 将验证结果存储到对应表单的 valid 属性中
      forms[index].valid = valid;
      // 通过 Promise 的 resolve 方法通知验证完成
      resolve();
    });
  });
};

const getVaBankCurrency = async () => {
  try {
    const data = await GetVaBankCurrency();
    state.currencyList = data || [];
  } catch {}
};

const getPhoneAreaCode = async () => {
  try {
    const data = await GetPhoneAreaCode();
    state.countryList = data || [];
  } catch {}
};

onMounted(async () => {
  getVaBankCurrency();
  getPhoneAreaCode();
  if (history.state.id) {
    currentId.value = history.state.id;
    try {
      const data = await getUserInfo({ id: currentId.value });
      for (let key in state.accountInfo) {
        if (key === "file_idcard_front") {
          state.accountInfo[key] = data["idcard_front"];
        } else if (key === "file_idcard_back") {
          state.accountInfo[key] = data["idcard_back"];
        } else if (key === "file_idcard_hand") {
          state.accountInfo[key] = data["idcard_hand"];
        } else {
          state.accountInfo[key] = data[key];
        }
      }
      // 以下用来展示图片
      state.file_idcard_front = data.file_idcard_front;
      state.file_idcard_back = data.file_idcard_back;
      state.file_idcard_hand = data.file_idcard_hand;
    } catch {}
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-upload-list--picture-card) {
  width: 192px;
  height: 112px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 192px;
  height: 112px;
}

:deep(.el-upload--picture-card) {
  width: 192px;
  height: 112px;
  display: flex;
  flex-direction: column;
  font-size: 12px;
}

:deep(.front_box .el-upload--picture-card) {
  display: none;
}

:deep(.back_box .el-upload--picture-card) {
  display: none;
}

:deep(.hand_box .el-upload--picture-card) {
  display: none;
}
.uploadDiv {
  margin-right: 30px;
}
.companyInfo {
  p {
    margin-bottom: 3%;
    font-size: 14px;
  }
}
.submitBtn {
  width: 200px;
}
</style>
